import axios from 'axios'
// import {BASE_URL} from  './interface'
import  store from "../store"

const service = axios.create({
  // baseURL: BASE_URL,
  // headers: {
  //   "Content-Type": "application/json;charset=utf-8"
  // }
});
// 请求拦截器(发送请求前做点事)
service.interceptors.request.use(
  config => {
    //如果存在token，添加token到请求头中
    if (store.state.token) {
      config.headers.token = store.state.token;
    }
      store.state.loading=true

      return config;
  },
  error => Promise.error(error)
);

//响应拦截器
service.interceptors.response.use(
  res => {
    console.log('response->res:', res)
    //根据后台返回的状态码而定
    res.data.code === 200 ? responseHandle(res) : errorHandle(res);
    setTimeout(()=>{
        store.state.loading=false
    },1000)
    return res
  },
  error => {
    const { response, message } = error;
    console.log('服务器系统状态码错误！', error)
    console.log('Status Code:', response.status)
    console.log('Error Message:', message)
    // errorHandleByStatus(response.status, response.data.status, response.data.message)
    return Promise.reject(error);
  }
);

//处理成功函数
function responseHandle(res) {
  //判断是否有返回token
  // 若有返回token（res.headers.authorization），保存token到
  if (res.headers.authorization) {
    console.log('发现新token',res.headers.authorization)
    store.commit('setToken', res.headers.authorization)
  }
}
//错误处理---------服务器状态码为2xx，后台状态码不为200的情景
function errorHandle(res) {
  let code = res.data.code
  let message = res.data.message
  // let msg = ''
  alert('后台状态码异常:', code, '->', message)
}


export default service


